package com.woan.api.servlet;

import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.woan.api.model.SysAdmininfo;
import com.woan.api.model.SysVideo;
import com.woan.api.services.UserClientServices;
import com.woan.api.services.VideoClientServices;
import com.woan.api.util.FuncDate;

public class VideoNotify extends HttpServlet {
	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Hashtable<String, String> hash = null;
		String str1 = null;
		str1 = request.getParameter("type");
		if (str1.equals("0")) {
			video_start(request, response);
		}

		if (str1.equals("2")) {
			video_save(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//判断视频的格式
		 //str1 = request.getParameter("type");
		 String str1 = request.getParameter("type");
		if (str1.equals("0")) {
			video_start(request, response);
		}
		if (str1.equals("2")) {
			video_save(request, response);
		}
		//doGet(request, response);
	}

	public void init() throws ServletException {
	}

	public void video_start(HttpServletRequest request, HttpServletResponse response)  {
		
		try {
			//判断视频输出格式
			String format = request.getParameter("format");
			if (format.startsWith("m3u8")) {
				m3u8_start(request,response);
			}else if (format.startsWith("flv")) {
				flv_start(request,response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}
	//flv 开始通知
	private void  flv_start(HttpServletRequest request,HttpServletResponse response){
		try {
			String groupname = "";
			String username = "";
			String vid = request.getParameter("hashed_id");
			System.err.println("视频vid............" + vid);
			String user_name = request.getParameter("author");
			System.err.println("视频author............" + user_name);
			String videoPath = request.getParameter("url");
			System.err.println("视频videoPath............" + videoPath);
			String videoSize = request.getParameter("size");
			System.err.println("视频size............" + videoSize);
			if (user_name.contains("|")) {
				String para[] = user_name.split("\\|");
				groupname = para[0];
				username = para[1];
			}
			ServletContext servletContext = this.getServletContext();
			WebApplicationContext wac = null;
			wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			UserClientServices userClientServices = (UserClientServices) wac.getBean("userClientServices");
			VideoClientServices videoClientServices = (VideoClientServices) wac.getBean("videoClientServices");
			SysAdmininfo user = userClientServices.findUserByGroupNameAndUserName(groupname,username);
			if (user!=null) {
				//判断用户是不是rtmp 推流
				if ("rtmp".equals(user.getCollect_type())) {
					//视频基本信息中插入一条数据
					System.err.println("用户的Id 是           （）（）（）（））（）（）（）（）（）（）（）           "+user.getSysRole().getRid()  );
					videoClientServices.inserVideoBasic(user, vid);
				}
			}else {
				//查询用户为空。
				System.err.println("_______________________查询用户为空 ________________________");
			}
			/*SysAdmininfo user = null;
			user = userClientServices.findUserByGroupNameAndUserName(groupname, username);
			if (user==null) {
				System.err.println("用户明为空。。。。。。。。。。。请检查用户信息");
			}
			//判断用户是不是rtmp 推流
			if ("rtmp".equals(user.getCollect_type())) {
				//视频基本信息中插入一条数据
				System.err.println("用户的Id 是                》》》》》》》》》》》》》》》》》》》》》           "+user.getRid()  );
				videoClientServices.inserVideoBasic(user, vid);
			}
			String uid = "";*/
			SysVideo sysVideo = new SysVideo();
			sysVideo.setSeqid(System.currentTimeMillis());
			sysVideo.setVid(vid);
			sysVideo.setBeginTime(FuncDate.FindCurSysTime1());
			sysVideo.setEndTime("");
			sysVideo.setPicture("");
			sysVideo.setStatus(0);
			sysVideo.setVideoLength("");
			sysVideo.setVideoPath(videoPath);
			sysVideo.setVideoSize(videoSize);
			sysVideo.setVideoType("android");
			sysVideo.setIsdel("1");
			System.out.println("下面push就开始了！");
			//videoClientServices.pushMessageFlv(sysVideo, user.getSysRole().getRid(), groupname, username);
			System.out.println("下面push就结束了！");
			System.out.println("flv直播插入视频");
			videoClientServices.insertVideo_flv(sysVideo,user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	private void  m3u8_start(HttpServletRequest request,HttpServletResponse response){
		try {
			String vid = request.getParameter("hashed_id");
			String user_name = request.getParameter("author");
			System.out.println("----------视频拍摄人是：》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》"+user_name);		
			String videoPath = request.getParameter("url");
			String videoSize = request.getParameter("size");
			String groupname = "";
			String username = "";
			if (user_name.contains("|")) 
			{
				String para[] = user_name.split("\\|");
				groupname = para[0];
				username = para[1];
			}
			ServletContext servletContext = this.getServletContext();     
	        WebApplicationContext wac = null;     
	        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);    
	        UserClientServices userClientServices = (UserClientServices) wac.getBean("userClientServices");
	        VideoClientServices videoClientServices = (VideoClientServices) wac.getBean("videoClientServices");
	        SysAdmininfo user = null;
	        //获取用户信息
	        user = userClientServices.findUserByGroupNameAndUserName(groupname, username);
	        
			String uid = "";
			if (user != null) {
				uid = user.getUid();
				videoClientServices.updateVideoState(uid,vid);
			} 
			//
			SysVideo sysVideo1 = videoClientServices.listOneVideoinfo(vid, "ios");	
			if(sysVideo1==null)
			{
				SysVideo sysVideo = new SysVideo();
				sysVideo.setVid(vid);
				sysVideo.setBeginTime(FuncDate.FindCurSysTime1());
				sysVideo.setEndTime("");
				sysVideo.setPicture("");
				sysVideo.setStatus(0);
				sysVideo.setVideoLength("");
				sysVideo.setVideoPath(videoPath);
				sysVideo.setVideoSize(videoSize);
				sysVideo.setVideoType("ios");
				sysVideo.setIsdel("1");		
				System.out.println("m3u8直播插入视频");
				videoClientServices.insertVideo(sysVideo,user.getSysRole().getRid(),groupname,username);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	public void videoStop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void video_save(HttpServletRequest request, HttpServletResponse response) {
		try {
			
			//判断视频输出格式
			String format = request.getParameter("format");
			if (format.startsWith("m3u8")) {
				m3u8_save(request,response);
			}else if (format.startsWith("flv")) {
				flv_save(request,response);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void  m3u8_save(HttpServletRequest request,HttpServletResponse response){
		System.out.println("---------------- M3u8存档通知 -----------");
		String vid = request.getParameter("hashed_id");
		String videoLength = request.getParameter("duration");
		String videoPath = request.getParameter("url");
		String user_name = request.getParameter("author");
		String groupname = "";
		String username = "";
		if (user_name.contains("|")) 
		{
			String para[] = user_name.split("\\|");
			groupname = para[0];
			username = para[1];
		}
		ServletContext servletContext = this.getServletContext();     
        WebApplicationContext wac = null;     
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);    
        UserClientServices userClientServices = (UserClientServices) wac.getBean("userClientServices");
        VideoClientServices videoClientServices = (VideoClientServices) wac.getBean("videoClientServices");
        SysAdmininfo user = null;
        user = userClientServices.findUserByGroupNameAndUserName(groupname, username);
		SysVideo sysVideo = videoClientServices.listOneVideoinfo(vid, "ios");	
		if (sysVideo!=null) {
			sysVideo.setVideoPath(videoPath);
			sysVideo.setPicture(videoPath+".jpg");
			sysVideo.setStatus(1);
			sysVideo.setEndTime(FuncDate.FindCurSysTime1());
			sysVideo.setVideoLength(videoLength);
			videoClientServices.updateVideo(sysVideo,user.getSysRole().getRid(),groupname,username);
			System.out.println("m3u8存档更新视频");
		}  
	}
	private void  flv_save(HttpServletRequest request,HttpServletResponse response){
		try {
			System.out.println("---------------- FLV存档通知 -----------");
			String vid = request.getParameter("hashed_id");
			String user_name = request.getParameter("author");
			System.err.println("视频id" + user_name);
			String videoPath = request.getParameter("url");
			System.err.println("视频url" + videoPath);
			String videoLength = request.getParameter("duration");
			String groupname = "";
			String username = "";
			if (user_name.contains("|")) {
				String para[] = user_name.split("\\|");
				groupname = para[0];
				username = para[1];
			}
			ServletContext servletContext = this.getServletContext();
			WebApplicationContext wac = null;
			wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			UserClientServices userClientServices = (UserClientServices) wac.getBean("userClientServices");
			VideoClientServices videoClientServices = (VideoClientServices) wac.getBean("videoClientServices");
			SysAdmininfo user = null;
			user = userClientServices.findUserByGroupNameAndUserName(groupname, username);
			List<SysVideo> sysVideo1 = videoClientServices.listVideoinfo(vid, "android");
			if (sysVideo1!=null&&sysVideo1.size() > 0) {
				for (int i = 0; i < sysVideo1.size(); i++) {
					SysVideo sysVideo = sysVideo1.get(i);
					sysVideo.setVideoPath(videoPath);
					sysVideo.setStatus(1);
					sysVideo.setEndTime(FuncDate.FindCurSysTime1());
					sysVideo.setVideoLength(videoLength);
					videoClientServices.updateVideo(sysVideo, user.getSysRole().getRid(), groupname, username);
				}
			}
			System.out.println("flv存档更新视频");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}